package com.ruolin.micro.gateway.server.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.ruolin.micro.gateway.server.constant.PropertiesConstant;
import com.ruolin.micro.gateway.server.forward.DubboGenericClient;
import com.ruolin.micro.gateway.server.route.resolver.PathVariableParameterResolver;
import com.ruolin.micro.gateway.server.route.resolver.RequestBodyParameterResolver;
import com.ruolin.micro.gateway.server.route.resolver.RequestFormParameterResolver;
import com.ruolin.micro.gateway.server.route.resolver.RequestParameterResolver;
import com.ruolin.micro.gateway.server.route.DefaultApplicationRouteLocator;
import com.ruolin.micro.gateway.server.route.RouteDefinitionLocator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class MicroGatewayConfig {
    @Autowired
    private Environment environment;

    @Bean
    public ConfigService configService() throws NacosException {
        String registry = environment.getProperty(PropertiesConstant.REGISTRY);
        if (registry == null) {
            throw new IllegalArgumentException("[dubbo.gateway.registry-address is null]");
        }

        ConfigService configService = NacosFactory.createConfigService("http://218.78.55.64:8848");
        return configService;
    }

    @Bean
    @ConditionalOnMissingBean
    public RouteDefinitionLocator routeDefinitionLocator(MicroGatewayProperties properties){
        return new PropertiesRouteDefinitionLocator(properties);
    }

    @Bean
    public RequestParameterResolver pathVariableParameterResolver(){
        return new PathVariableParameterResolver();
    }

    @Bean
    public RequestParameterResolver requestBodyParameterResolver(){
        return new RequestBodyParameterResolver();
    }

    @Bean
    public RequestParameterResolver requestFormParameterResolver(){
        return new RequestFormParameterResolver();
    }

    @Bean
    public DubboGenericClient dubboGenericClient(){
        return new DubboGenericClient();
    }

    @Bean
    public DefaultApplicationRouteLocator defaultApplicationRouteLocator(){
        return new DefaultApplicationRouteLocator();
    }
}
